<template>
  <div>
    课程-视频上传 lessonId:{{ courseId }} ,{{ $route.query }}
    <el-form label-width="80px">
      <el-form-item label="课程名称">
        <el-input />
      </el-form-item>
      <el-form-item label="图片文件">
        <input type="file" @change="imageFile = $event.target.files[0]" />
      </el-form-item>
      <el-form-item label="视频文件">
        <input type="file" @change="videoFile = $event.target.files[0]" />
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="handleUpload">开始上传</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </el-form-item>
    </el-form>
    <div class="statusInfo" v-if="status.section > 0">
      <div>
        上传进度:{{ status.section > 1 ? "已完成" : status.uploadPercent }}
      </div>
      <div v-if="status.section > 1">
        转码进度:{{
          status.transCodePercent >= 100 ? "已完成" : status.transCodePercent
        }}
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { getAliyunImagUploadAddressAdnAuth, getAliyunTransCodePercent, getAliyunVideoUploadAddressAdnAuth, postAliyunTransCode } from '@/services/course'
import Vue from 'vue'
export default Vue.extend({
  name: 'CourseVideoUpload',
  props: {
    courseId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      videoFile: null,
      imageFile: null,
      clearLast: null as null|Function,
      // uploader: null as any,
      status: {
        section: 0, // 0未上传,1正在上传,2转码
        uploadPercent: 0,
        transCodePercent: 0,
        beginUpload () {
          this.section = 1
          this.uploadPercent = 0
        },
        updateUploadPercent (percent: number) {
          this.uploadPercent = percent
        },
        beginTransCode () {
          this.section = 2
          this.transCodePercent = 0
        },
        updateTransCodePercent (percent: number) {
          this.transCodePercent = percent
        }
      }
    }
  },
  methods: {
    initUpload () {
      const { status } = this
      const { sectionId, lessonId } = this.$route.query as { sectionId: string; lessonId: string }
      let imageUrl = ''; let videoId = ''
      const toClear = [] as Function[]
      const uploader = new window.AliyunUpload.Vod({
        // 阿里账号ID，必须有值
        userId: '1618139964448548',
        // 上传到视频点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
        region: '',
        // 分片大小默认1 MB，不能小于100 KB
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        async onUploadstarted (uploadInfo: any) {
          // setUploadAuthAndAddress
          let resp = null as any
          if (uploadInfo.isImage) {
            const { data } = await getAliyunImagUploadAddressAdnAuth()
            imageUrl = data.data.imageUrl
            resp = data.data
          } else {
            const { data } = await getAliyunVideoUploadAddressAdnAuth(uploadInfo.file.name, imageUrl)
            resp = data.data
            videoId = resp.videoId
          }
          //           fileURL: "https://outin-61fd129aa62411eaa4ef00163e1c94a4.oss-cn-shanghai.aliyuncs.com/image/cover/099E641AE2204204835311D568B62F49-6-2.png"
          // imageId: "9e8c88cbdd1f4992a0163ab101dc11f0"
          // imageURL: "https://outin-61fd129aa62411eaa4ef00163e1c94a4.oss-cn-shanghai.aliyuncs.com/image/cover/099E641AE2204204835311D568B62F49-6-2.png?Expires=1610012007&OSSAccessKeyId=LTAIVVfYx6D0HeL2&Signature=qoSLql%2B8XbZJ3v5Ut64W1T5HJuk%3D"
          // requestId: "45A2F88B-6DED-48A8-B304-7A9D2E8E2CD3"
          // uploadAddress: "eyJFbmRwb2ludCI6Imh0dHBzOi8vb3NzLWNuLXNoYW5naGFpLmFsaXl1bmNzLmNvbSIsIkJ1Y2tldCI6Im91dGluLTYxZmQxMjlhYTYyNDExZWFhNGVmMDAxNjNlMWM5NGE0IiwiRmlsZU5hbWUiOiJpbWFnZS9jb3Zlci8wOTlFNjQxQUUyMjA0MjA0ODM1MzExRDU2OEI2MkY0OS02LTIucG5nIn0="
          // uploadAuth: "eyJTZWN
          console.log('setUploadAuthAndAddress:', uploadInfo, resp.uploadAuth, resp.uploadAddress, resp.imageId || resp.videoId)
          uploader.setUploadAuthAndAddress(uploadInfo, resp.uploadAuth, resp.uploadAddress, resp.imageId || resp.videoId)
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo: any) {
          console.log('onUploadSucceed:', uploadInfo)
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo: any, code: unknown, message: unknown) {
          console.warn('onUploadFailed:', uploadInfo, code, message)
        },
        // 文件上传进度，单位：字节
        onUploadProgress: function (uploadInfo: any, totalSize: number, loadedPercent: number) {
          console.log('onUploadProgress:', uploadInfo, totalSize, loadedPercent)
          status.updateUploadPercent(loadedPercent * 100)
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo: any) {
          console.warn('onUploadTokenExpired:', uploadInfo)
        },
        // 全部文件上传结束
        onUploadEnd: async (uploadInfo: any) => {
          status.beginTransCode()
          console.log('uploadEnd:', uploadInfo)
          const { data } = await postAliyunTransCode({ sectionId, lessonId, fileId: videoId, fileName: (this.videoFile as any).name })
          console.log('postAliyunTransCode:', data)
          // 检查转码进度
          let count = 0 // 由于接口不可用，在此使用count 作为测试代码演示demo
          const timer = setInterval(async () => {
            const { data: res } = await getAliyunTransCodePercent(lessonId)
            console.log('检查转码进度:', res)
            status.updateTransCodePercent(count)
            if (count++ >= 100) {
              clearInterval(timer)
            }
          }, 3000)
          toClear.push(() => clearInterval(timer))
        }
      })
      return {
        uploader,
        clear () {
          for (const fn of toClear) {
            fn()
          }
        }
      }
    },
    handleUpload () {
      const { uploader, clear } = this.initUpload()
      if (this.clearLast) {
        this.clearLast()
      }
      this.clearLast = clear
      const { imageFile, videoFile } = this
      uploader.addFile(imageFile, null, null, null, '{"Vod":{}}')
      uploader.addFile(videoFile, null, null, null, '{"Vod":{}}')
      this.status.beginUpload()
      uploader.startUpload()
    }

  }
})
</script>
